package com.oswift.cms.web.backstage;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.cms.entity.AdminBean;
import com.oswift.cms.entity.CompanyBean;
import com.oswift.cms.entity.ErrorBean;
import com.oswift.cms.entity.MessageBean;
import com.oswift.cms.entity.PageBean;
import com.oswift.cms.entity.WebConfigBean;
import com.oswift.cms.service.ICompanyService;
import com.oswift.cms.utils.PageCode;
import com.oswift.cms.utils.Field.PageName;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.exception.PlatException;

@Controller
@RequestMapping("/security")
public class CompanyAction extends BaseAction
{
    /**
     * spring注入CompanyServiceImpl对象
     */
    @Resource
    private ICompanyService companyService;

    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(CompanyAction.class);

    /**
     *
     * 初始化company页面表
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadAddCompany", method = RequestMethod.GET)
    public ModelAndView loadAddCompany()
    {
        ModelAndView mv = null;
        try
        {
            Map<String, Object> map = companyService.getCompanyOtherInfo();

            mv = new ModelAndView(PageName.COMPANY);
            mv.addObject(METHOD, METHOD_ADD);
            mv.addObject("map", map);
        }
        catch (PlatException e)
        {
            log.error("Load company page is error.", e);
        }
        return mv;
    }

    /**
     *
     * 修改load页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadUpdateCompany", method = RequestMethod.GET)
    public ModelAndView loadUpdateCompany(@RequestParam("id")
    int id)
    {
        ModelAndView mv = null;
        try
        {
            if (id > 0)
            {
                mv = new ModelAndView(PageName.COMPANY);
                Map<String, Object> map = companyService.getCompanyDetail(id);
                // WebConfigBean webBean = companyService.webConfigDetail(id);
                mv.addObject("map", map);
                // mv.addObject("webBean", webBean);
                mv.addObject(METHOD, METHOD_UPDATE);
            }
            else
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
            }
        }
        catch (PlatException e)
        {
            log.error("Load UpdateCompany page is error.id=" + id, e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 保存公司信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/addCompany", method = RequestMethod.POST)
    @ResponseBody
    public Object addCompany(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            CompanyBean companyBean = getCompanyBean(request);
            if (StringUtil.isEmpty(companyBean.getCompanyName())
                    || StringUtil.isEmpty(companyBean.getReferred()))
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }
            boolean isSuccess = companyService.save(companyBean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.COMPANY_SAVE_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.COMPANY_SAVE_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.COMPANY_SAVE_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to save company info error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 从页面获取公司信息
     *
     * @author zhuou
     */
    private CompanyBean getCompanyBean(HttpServletRequest request)
    {
        CompanyBean bean = new CompanyBean();
        String companyName = request.getParameter("companyName");
        String referred = request.getParameter("referred");
        String companyPropertieId = request.getParameter("companyPropertieId");
        String companyIndustryId = request.getParameter("companyIndustryId");
        String companyScaleId = request.getParameter("companyScaleId");
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String district = request.getParameter("district");
        String address = request.getParameter("address");
        String zipCode = request.getParameter("zipCode");
        String contact = request.getParameter("contact");
        String telephone = request.getParameter("telephone");
        String companyIntr = request.getParameter("companyIntr");
        String email = request.getParameter("email");
        String mobile = request.getParameter("mobile");
        String remark = request.getParameter("remark");
        String companyId = request.getParameter("companyId");

        bean.setAddress(address);
        bean.setCity(city);
        if (!StringUtil.isEmpty(companyIndustryId))
        {
            bean.setCompanyIndustryId(Integer.valueOf(companyIndustryId));
        }
        bean.setCompanyIntr(StringUtil.trim(companyIntr));
        bean.setCompanyName(StringUtil.trim(companyName));
        if (!StringUtil.isEmpty(companyPropertieId))
        {
            bean.setCompanyPropertieId(Integer.valueOf(companyPropertieId));
        }
        if (!StringUtil.isEmpty(companyScaleId))
        {
            bean.setCompanyScaleId(Integer.valueOf(companyScaleId));
        }
        if (!StringUtil.isEmpty(companyId))
        {
            bean.setCompanyId(Integer.valueOf(companyId));
        }
        else
        {
            bean.setCompanyId(-100);
        }

        bean.setContact(StringUtil.trim(contact));
        bean.setDistrict(StringUtil.trim(district));
        bean.setEmail(StringUtil.trim(email));
        bean.setMobile(StringUtil.trim(mobile));
        bean.setProvince(StringUtil.trim(province));
        bean.setReferred(StringUtil.trim(referred));
        bean.setRemark(StringUtil.trim(remark));
        bean.setTelephone(StringUtil.trim(telephone));
        bean.setZipCode(StringUtil.trim(zipCode));

        return bean;
    }

    /**
     *
     * 获取站点配置信息
     *
     * @author zhuou
     */
    private WebConfigBean getWebConfigBean(HttpServletRequest request)
    {
        WebConfigBean bean = new WebConfigBean();
        String siteName = request.getParameter("siteName");
        String companyId = request.getParameter("companyId");
        String siteUrl = request.getParameter("siteUrl");
        String logoUrl = request.getParameter("logoUrl");
        String copyright = request.getParameter("copyright");
        String metaKeywords = request.getParameter("metaKeywords");
        String metaDescription = request.getParameter("metaDescription");
        String upLoadImgType = request.getParameter("upLoadImgType");
        String uploadFileType = request.getParameter("uploadFileType");
        String errorPagePath = request.getParameter("errorPagePath");
        String siteId = request.getParameter("siteId");
        String imgThumbWidth = request.getParameter("imgThumbWidth");
        String imgThumbHeight = request.getParameter("imgThumbHeight");

        if (StringUtil.isEmpty(companyId))
        {
            bean.setCompanyId(0);
        }
        else
        {
            bean.setCompanyId(Integer.valueOf(companyId));
        }
        bean.setCopyright(StringUtil.trim(copyright));
        bean.setLogoUrl(StringUtil.trim(logoUrl));
        bean.setMetaDescription(StringUtil.trim(metaDescription));
        bean.setMetaKeywords(StringUtil.trim(metaKeywords));
        bean.setSiteName(StringUtil.trim(siteName));
        bean.setSiteUrl(StringUtil.trim(siteUrl));
        bean.setUploadFileType(StringUtil.trim(uploadFileType));
        bean.setUpLoadImgType(StringUtil.trim(upLoadImgType));
        if (!StringUtil.isEmpty(errorPagePath))
        {
            bean.setErrorPagePath(StringUtil.trim(errorPagePath));
        }
        if (!StringUtil.isEmpty(siteId))
        {
            bean.setSiteId(Integer.valueOf(siteId));
        }
        else
        {
            bean.setSiteId(-100);
        }
        if (!StringUtil.isBlank(imgThumbWidth))
        {
            bean.setImgThumbWidth(Integer.valueOf(imgThumbWidth));
        }
        else
        {
            bean.setImgThumbWidth(100);
        }
        if (!StringUtil.isBlank(imgThumbHeight))
        {
            bean.setImgThumbHeight(Integer.valueOf(imgThumbHeight));
        }
        else
        {
            bean.setImgThumbHeight(100);
        }

        return bean;
    }

    /**
     *
     * 获取公司列表
     *
     * @author zhuou
     */
    @RequestMapping(value = "/getCompanyList", method = RequestMethod.GET)
    public ModelAndView getCompanyList(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String keyword = request.getParameter("keyword");
            if (!StringUtil.isEmpty(keyword))
            {
                keyword = decodeKeyword(keyword);
            }
            else
            {
                keyword = null;
            }

            int pageNum = DEFAULT_PAGENUM;
            if (!StringUtil.isEmpty(request.getParameter("pageNum")))
            {
                pageNum = Integer.valueOf(request.getParameter("pageNum"));
            }

            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();
            PageBean<CompanyBean> pageBean = companyService.getCompanyList(
                    keyword, pageNum, this.pageRecordNum, companyId);
            pageBean.setPageRecordNum(this.pageRecordNum);

            mv = new ModelAndView(PageName.COMPANYLIST);
            mv.addObject("pageBean", pageBean);
        }
        catch (PlatException e)
        {
            log.error("Get company list is error.", e);
        }
        return mv;
    }

    /**
     *
     * 公司页面详情
     *
     * @author zhuou
     */
    @RequestMapping(value = "/companyDetail", method = RequestMethod.GET)
    public ModelAndView companyDetail(HttpServletRequest request)
    {
        String sId = request.getParameter("id");
        ModelAndView mv = null;
        try
        {
            if (!StringUtil.isEmpty(sId))
            {
                int id = Integer.valueOf(sId);
                mv = new ModelAndView(PageName.COMPANYDETAIL);
                CompanyBean bean = companyService.companyDetail(id);
                WebConfigBean webBean = companyService.webConfigDetail(id);
                mv.addObject("bean", bean);
                mv.addObject("webBean", webBean);
            }
            else
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
            }
        }
        catch (PlatException e)
        {
            log.error("Get companyDetail page is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 修改公司信息
     *
     * @author zhuou
     *
     */
    @RequestMapping(value = "/updateCompany", method = RequestMethod.POST)
    @ResponseBody
    public Object updateCompany(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            CompanyBean companyBean = getCompanyBean(request);
            if (companyBean.getCompanyId() == -100
                    || StringUtil.isEmpty(companyBean.getCompanyName())
                    || StringUtil.isEmpty(companyBean.getReferred()))
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }
            boolean isSuccess = companyService.update(companyBean);

            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.COMPANY_UPDATE_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.COMPANY_UPDATE_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.COMPANY_UPDATE_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to update company info error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 初始化WebConfig新增页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadAddWebConfig", method = RequestMethod.GET)
    public ModelAndView loadAddWebConfig(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            int companyId = this.getAdmin(request).getCompanyID();
            List<CompanyBean> list = companyService.getCompanysbyCId(companyId);
            mv = new ModelAndView(PageName.WEBCONFIG);
            mv.addObject(METHOD, METHOD_ADD);
            mv.addObject("list", list);
        }
        catch (PlatException e)
        {
            log.error("Load loadAddWebConfig page is error.", e);
        }
        return mv;
    }

    /**
     *
     * 获取站点配置信息列表
     *
     * @author zhuou
     */
    @RequestMapping(value = "/getWebConfigList", method = RequestMethod.GET)
    public ModelAndView getWebConfigList(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String keyword = request.getParameter("keyword");
            if (!StringUtil.isEmpty(keyword))
            {
                keyword = decodeKeyword(keyword);
            }
            else
            {
                keyword = null;
            }

            int pageNum = DEFAULT_PAGENUM;
            if (!StringUtil.isEmpty(request.getParameter("pageNum")))
            {
                pageNum = Integer.valueOf(request.getParameter("pageNum"));
            }

            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();
            PageBean<WebConfigBean> pageBean = companyService.getWebConfigList(
                    keyword, pageNum, this.pageRecordNum, companyId);
            pageBean.setPageRecordNum(this.pageRecordNum);

            mv = new ModelAndView(PageName.WEBCONFIGLIST);
            mv.addObject("pageBean", pageBean);
        }
        catch (PlatException e)
        {
            log.error("Get getWebConfigList is error.", e);
        }
        return mv;
    }

    /**
     *
     * 保存站点信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/addWebConfig", method = RequestMethod.POST)
    @ResponseBody
    public Object addWebConfig(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            WebConfigBean webBean = getWebConfigBean(request);
            if (webBean.getCompanyId() <= 0
                    || StringUtil.isEmpty(webBean.getSiteName())
                    || StringUtil.isEmpty(webBean.getSiteUrl())
                    || StringUtil.isEmpty(webBean.getUploadFileType())
                    || StringUtil.isEmpty(webBean.getUpLoadImgType()))
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }

            webBean.setCreateUser(this.getAdmin(request).getAdminName());
            boolean isSuccess = companyService.saveWebConfig(webBean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.WEBCONFIG_SAVE_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.WEBCONFIG_SAVE_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.WEBCONFIG_SAVE_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to addWebConfig info error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 站点页面详情
     *
     * @author zhuou
     */
    @RequestMapping(value = "/webConfigDetail", method = RequestMethod.GET)
    public ModelAndView webConfigDetail(HttpServletRequest request)
    {
        String sId = request.getParameter("id");
        ModelAndView mv = null;
        try
        {
            if (!StringUtil.isEmpty(sId))
            {
                int id = Integer.valueOf(sId);
                mv = new ModelAndView(PageName.WEBCONFIGDETAIL);
                WebConfigBean webBean = companyService.webConfigDetail(id);
                mv.addObject("webBean", webBean);
            }
            else
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
            }
        }
        catch (PlatException e)
        {
            log.error("Get webConfigDetail is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 修改站点load页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadUpdateWebConfig", method = RequestMethod.GET)
    public ModelAndView loadUpdateWebConfig(HttpServletRequest request,
            @RequestParam("id")
            int id)
    {
        ModelAndView mv = null;
        try
        {
            if (id > 0)
            {
                int companyId = this.getAdmin(request).getCompanyID();
                List<CompanyBean> list = companyService
                        .getCompanysbyCId(companyId);

                mv = new ModelAndView(PageName.WEBCONFIG);
                WebConfigBean webBean = companyService.webConfigDetail(id);
                mv.addObject("webBean", webBean);
                mv.addObject(METHOD, METHOD_UPDATE);
                mv.addObject("list", list);
            }
            else
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
            }
        }
        catch (PlatException e)
        {
            log.error("Load loadUpdateWebConfig page is error.id=" + id, e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 修改站点信息
     *
     * @author zhuou
     *
     */
    @RequestMapping(value = "/updateWebConfig", method = RequestMethod.POST)
    @ResponseBody
    public Object updateWebConfig(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            WebConfigBean webBean = getWebConfigBean(request);

            if (StringUtil.isEmpty(webBean.getSiteName())
                    || StringUtil.isEmpty(webBean.getSiteUrl())
                    || StringUtil.isEmpty(webBean.getUploadFileType())
                    || StringUtil.isEmpty(webBean.getUpLoadImgType()))
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }
            boolean isSuccess = companyService.updateWebConfig(webBean);

            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.WEBCONFIG_UPDATE_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.WEBCONFIG_UPDATE_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.WEBCONFIG_UPDATE_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("Fail to updateWebConfig info error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 根据站点Id删除站点信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/delWebConfig", method = RequestMethod.GET)
    @ResponseBody
    public Object delWebConfig(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }

            // 获取绝对路径
            String realPath = request.getSession().getServletContext()
                    .getRealPath("");
            boolean isSuccess = companyService.delWebConfig(
                    Integer.valueOf(id), realPath);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.WEBCONFIG_DEL_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.WEBCONFIG_DEL_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.WEBCONFIG_DEL_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("delWebConfig's Action is error.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
        }

        return messBean;
    }

    /**
     *
     * 注入CompanyServiceImpl对象
     *
     * @author zhuou
     * @param companyService
     */
    public void setCompanyService(ICompanyService companyService)
    {
        this.companyService = companyService;
    }
}
